﻿using System;
using System.Diagnostics;
using System.Linq;
using CoreEx.Common.Logging;
using CoreEx.Database.Client;
using LinFu.IoC.Interfaces;
using LinFu.IoC;
namespace CoreEx.Database.Metadata.ModelGenerator
{
    class Program
    {
        private static readonly IServiceContainer _serviceContainer = Services.ServiceLocator.Container;
        
        static void Main(string[] args)
        {
            string connectionString = args.Where(a => a.StartsWith(@"/C")).FirstOrDefault();
            string outputDirectory = args.Where(a => a.StartsWith(@"/O")).FirstOrDefault();
            string modelNamespace = args.Where(a => a.StartsWith(@"/N")).FirstOrDefault();
            string providerName  = args.Where(a => a.StartsWith(@"/P")).FirstOrDefault();
           
           
            
            
           
            
            if (string.IsNullOrEmpty(connectionString) ||
                string.IsNullOrEmpty(outputDirectory) ||
                string.IsNullOrEmpty(modelNamespace) ||
                string.IsNullOrEmpty(providerName))
            {
                ShowUsage();
                return;
            }
            connectionString = connectionString.Substring(3);
            outputDirectory = outputDirectory.Substring(3);
            modelNamespace = modelNamespace.Substring(3);
            providerName = providerName.Substring(3);

            try
            {
                Generate(connectionString, outputDirectory, modelNamespace, providerName);
            }
            catch (Exception ex)
            {
                Console.WriteLine("An error has occurred during generation: {0}", ex);
                Trace.TraceError("An error has occurred during generation: {0}", ex);
                
            }
            
        }

        private static void Generate(string connectionString, string outputDirectory, string modelNamespace, string providerName)
        {
            _serviceContainer.GetService<IDbConnectionInfoProvider>().AddConnection(modelNamespace, providerName, connectionString);                                            
            var generator = _serviceContainer.GetService<IModelGenerator>();
            var metadataRepository = _serviceContainer.GetService<IMetadataRepository>(modelNamespace,false);
            generator.Generate(metadataRepository,modelNamespace,outputDirectory,false);
        }


        private static void ShowUsage()
        {
            Console.WriteLine(@"ModelGenerator.exe /C=[ConnectionString] /P=[ProviderName] /O=[OutputDirectory] /N=[Namespace]");
            Console.WriteLine("Press any key to continue");
            Console.ReadLine();
        }
    }
}
